const fs = require('fs');
const path = require('path');
const BaseIpcHandler = require('../BaseIpcHandler');

class LoadTileImageHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> LoadTileImageHandler params = ', params);
        const { x, y, zoom } = params;
        const image_path = path.join(this.app.userDataPath, 'tiles', `zoom${zoom}`, `${x}`, `${y}.png`);

        // 检查文件是否存在
        let result = { code: -1, msg: 'Tile not exist!' };
        if (fs.existsSync(image_path)) {
            result = { code: 0, msg: 'Tile exists!' };
        }

        // 业务逻辑 && 返回结果
        if (event.from === 'localserver') {
            if (result.code == 0) {
                event.resp.sendFile(image_path, (err) => {
                    if (err) {
                        console.error('Error sending file:', err);
                        event.resp.status(404).send('File not found');
                    }
                });
            } else {
                event.resp.send(result);
            }
        } else {
            if (result.code == 0) {
                return fs.readFileSync(image_path);
            } else {
                return result;
            }
        }
    }
}

module.exports = LoadTileImageHandler;
